package com.mingtang.online.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.mingtang.online.R;
import com.mingtang.online.activity.BaseWebActivity;
import com.mingtang.online.activity.HongBaoWebActivity;
import com.mingtang.online.adapter.IndexAdapter;
import com.mingtang.online.bean.FenLeiBean;
import com.mingtang.online.bean.QianDao;
import com.mingtang.online.bean.ShangPin;
import com.mingtang.online.changliang.Const;
import com.mingtang.online.http.MyOkhttp;
import com.mingtang.online.http.callback.StringNoDialogCallback;
import com.mingtang.online.http.request.BaseRequest;
import com.mingtang.online.layoutmanager.FullyGridLayoutManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;


@SuppressLint("ValidFragment")
public class SimpleCardFragment2 extends BaseFragment {


    Unbinder unbinder;
    @BindView(R.id.img_sign)
    ImageView imgSign;
    @BindView(R.id.text_sign)
    TextView textSign;
    @BindView(R.id.layout_sign)
    LinearLayout layoutSign;
    @BindView(R.id.img_youhui)
    ImageView imgYouhui;
    @BindView(R.id.text_youhui)
    TextView textYouhui;
    @BindView(R.id.layout_youhui)
    LinearLayout layoutYouhui;
    @BindView(R.id.img_baoyou)
    ImageView imgBaoyou;
    @BindView(R.id.text_baoyou)
    TextView textBaoyou;
    @BindView(R.id.layout_baoyou)
    LinearLayout layoutBaoyou;
    @BindView(R.id.img_mai)
    ImageView imgMai;
    @BindView(R.id.text_mai)
    TextView textMai;
    @BindView(R.id.layout_mai)
    LinearLayout layoutMai;
    @BindView(R.id.img_fuli)
    ImageView imgFuli;
    @BindView(R.id.text_fuli)
    TextView textFuli;
    @BindView(R.id.layout_fuli)
    LinearLayout layoutFuli;
    @BindView(R.id.recycler_view_test_rv)
    RecyclerView recyclerViewTestRv;
  /*  @BindView(R.id.xrefreshview)
    XRefreshView xrefreshview;*/

    @BindView(R.id.img_youhiu)
    ImageView imgYouhiu;

    @BindView(R.id.img_shijian)
    ImageView imgShijian;
    @BindView(R.id.img_jiukuaijiu)
    ImageView imgJiukuaijiu;
    @BindView(R.id.img_zhuanqianzhongxin)
    ImageView imgZhuanqianzhongxin;

    @BindView(R.id.layout_Linear)
    LinearLayout layoutLinear;

    @BindView(R.id.scrollview)
    ScrollView scrollview;
    @BindView(R.id.v4_webview)
    com.tencent.smtt.sdk.WebView v4Webview;
    private String mTitle;

    public List<String> images = new ArrayList<>();
    IndexAdapter testAdapter;

    public List<String> receiveData = new ArrayList<>();
    private int mLoadCount = 0;


    public static SimpleCardFragment2 getInstance(String title) {
        SimpleCardFragment2 sf = new SimpleCardFragment2();
        sf.mTitle = title;
        return sf;
    }

    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(com.tencent.smtt.sdk.WebView webView, int i) {

        }
    };
//九块九
    //    http://www.50210.com.cn/app/index.php?i=3&c=entry&price2=9.9&pid=mm_120991317_38116267_139518914&do=newcat&m=tiger_newhu

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private View headerView;
    List<FenLeiBean.ContentBean> contentBean = new ArrayList<>();
    List<QianDao.ContentBean> contentBean2 = new ArrayList<>();
    List<ShangPin.ContentBean> contentBean3 = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card2, null);

        unbinder = ButterKnife.bind(this, v);
        if (images != null) {
            images.clear();
        }


        for (int i = 0; i < 30; i++) {
            receiveData.add("这是第" + i + "条数据");
        }
        recyclerViewTestRv.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2));
        recyclerViewTestRv.setNestedScrollingEnabled(false);

/*
        //设置刷新完成以后，headerview固定的时间
        xrefreshview.setPinnedTime(1000);
        xrefreshview.setMoveForHorizontal(true);
        xrefreshview.setPullLoadEnable(true);
        xrefreshview.setAutoLoadMore(false);

        xrefreshview.enableReleaseToLoadMore(true);
        xrefreshview.enableRecyclerViewPullUp(true);
        xrefreshview.enablePullUpWhenLoadCompleted(true);
        //设置静默加载时提前加载的item个数
//        xefreshView1.setPreLoadCount(4);
        //设置Recyclerview的滑动监听
        xrefreshview.setXRefreshViewListener(this);*/

        getAdvData();
        getQianDaoData();
        getShop();
        initWebView();

        v4Webview.loadUrl(Const.MODEL_URL + "i=3&c=entry&type=" + mTitle + "&do=newcatapp&m=tiger_newhu");

        return v;
    }

    public void initWebView() {
        v4Webview.clearCache(true);

//        v4Webview.setWebChromeClient(chromeClient);
        v4Webview.setWebChromeClient(chromeClient);
        v4Webview.getSettings().setUseWideViewPort(true);

        v4Webview.getSettings().setLoadWithOverviewMode(true);
        v4Webview.getSettings().setSavePassword(true);
        v4Webview.getSettings().setSaveFormData(true);
        v4Webview.getSettings().setJavaScriptEnabled(true);

        // enable navigator.geolocation
        v4Webview.getSettings().setGeolocationEnabled(true);
        v4Webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");

        v4Webview.requestFocus();
        v4Webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4Webview.getSettings().getUserAgentString();
        v4Webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4Webview.addJavascriptInterface(new JsInterfaces(getActivity()),
                "AndroidWebView");
        v4Webview.getSettings().setBuiltInZoomControls(true);
        v4Webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4Webview.getSettings().setDomStorageEnabled(true);

        v4Webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);

        v4Webview.getSettings().setAllowFileAccess(true);
        v4Webview.getSettings().setAppCacheEnabled(true);
        v4Webview.getSettings().setJavaScriptEnabled(true);
//        v4Webview.getSettings().setAppCachePath(appCachePath);
        v4Webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4Webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4Webview.getSettings().setDefaultTextEncodingName("utf-8");

        v4Webview.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent ev) {

                ((WebView) v).requestDisallowInterceptTouchEvent(true);

                return false;
            }
        });
        v4Webview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {


                return true;
            }


        });
    }

    public class JsInterfaces {
        private Context mContext;

        //js交互
// 在js中调用window.AndroidWebView.appZTBIn(amount)，便会触发此方法。
        public JsInterfaces(Context mContext) {
            super();
            this.mContext = mContext;
        }

        //转入
        @JavascriptInterface
        public void app_detail(String amount) {
        }
    }


    public void getAdvData() {
        //轮播图
//http://www.50210.com.cn/app/index.php?i=3&c=entry&do=getad3&m=mingtang

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("do", "getad3")
                .params("m", "mingtang")
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);


                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");

                        FenLeiBean fenLeiBean = new FenLeiBean();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, FenLeiBean.class);
                        contentBean = fenLeiBean.getContent();
                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(0).getPic())
                                .placeholder(R.mipmap.ic_launcher)
                                .crossFade()
                                .into(imgYouhiu);
                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(1).getPic())
                                .placeholder(R.mipmap.ic_launcher)
                                .crossFade()
                                .into(imgShijian);

                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(2).getPic())
                                .placeholder(R.mipmap.ic_launcher)
                                .crossFade()
                                .into(imgJiukuaijiu);

                        Glide.with(getActivity())
                                .load("http://www.50210.com.cn/attachment/" + contentBean.get(3).getPic())
                                .placeholder(R.mipmap.ic_launcher)
                                .crossFade()
                                .into(imgZhuanqianzhongxin);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);

                    }
                });

    }

    public void getQianDaoData() {

        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("do", "getad2")
                .params("m", "mingtang")
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);


                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                       /* AccessToken accessToken = new AccessToken();
                        Gson gson = new Gson();
                        accessToken = gson.fromJson(s, AccessToken.class);*/
                        QianDao fenLeiBean = new QianDao();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, QianDao.class);
                        contentBean2 = fenLeiBean.getContent();
                        try {

                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(0).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgSign);
                            textSign.setText(contentBean2.get(0).getTitle());
                           /* Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(1).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgYouhiu);*/
                            textYouhui.setText(contentBean2.get(1).getTitle());
                        /*    Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(1).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgJiukuaijiu);*/
                            textBaoyou.setText(contentBean2.get(2).getTitle());
                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(2).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgMai);
                            textMai.setText(contentBean2.get(3).getTitle());
                            Glide.with(getActivity())
                                    .load("http://www.50210.com.cn/attachment/" + contentBean.get(3).getPic())
                                    .placeholder(R.mipmap.ic_launcher)
                                    .crossFade()
                                    .into(imgFuli);
                            textFuli.setText(contentBean2.get(4).getTitle());
                        } catch (Exception e) {

                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);

                    }
                });

    }


    public void getShop() {
        //商品
//http://www.50210.com.cn/app/index.php?i=3&c=entry&rate=30&do=Newcatpost&m=tiger_newhu


        MyOkhttp.post(Const.MODEL_URL)
                .tag(this)
                .params("i", "3")
                .params("c", "entry")
                .params("rate", "30")
                .params("do", "Newcatpost")
                .params("m", "tiger_newhu")
                .execute(new StringNoDialogCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showLoading();

                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");
                        Log.d(s, "eeeeeeeeeeeeeeeeeeeee");

                        ShangPin fenLeiBean = new ShangPin();
                        Gson gson = new Gson();
                        fenLeiBean = gson.fromJson(s, ShangPin.class);
                        contentBean3 = fenLeiBean.getContent();
                        testAdapter = new IndexAdapter(contentBean3);
                        testAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                BaseWebActivity.start(getContext(), 0, "http://www.baidu.com");
                            }
                        });


                        recyclerViewTestRv.setAdapter(testAdapter);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        dismissLoading();
                    }

                    @Override
                    public void onAfter(String s, Exception e) {
                        super.onAfter(s, e);
                        dismissLoading();
                    }
                });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.img_sign, R.id.text_sign, R.id.layout_sign, R.id.img_youhui, R.id.text_youhui, R.id.layout_youhui, R.id.img_baoyou, R.id.text_baoyou, R.id.layout_baoyou, R.id.img_mai, R.id.text_mai, R.id.layout_mai, R.id.img_fuli, R.id.text_fuli, R.id.layout_fuli})
    public void onViewClicked(View view) {
        Intent intent;

        switch (view.getId()) {


            case R.id.img_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.text_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_sign:
//                Toast.makeText(getActivity(), "点击了签到", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.img_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.text_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.layout_youhui:
                EventBus.getDefault().post(0);
                break;
            case R.id.img_baoyou:
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.text_baoyou:
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_baoyou:
//                Toast.makeText(getActivity(), "点击了9.9包邮", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.img_mai:
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.text_mai:
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_mai:
//                Toast.makeText(getActivity(), "值得买", Toast.LENGTH_SHORT).show();
                intent = new Intent(getActivity(), HongBaoWebActivity.class);
                startActivity(intent);
                break;
            case R.id.img_fuli:
                EventBus.getDefault().post(1);
                break;
            case R.id.text_fuli:
                EventBus.getDefault().post(1);
                break;
            case R.id.layout_fuli:
                EventBus.getDefault().post(1);
                break;
        }
    }


}